import {inject} from 'aurelia-dependency-injection';
import {Project, ProjectItem, CLIOptions, UI} from 'aurelia-cli';

@inject(Project, CLIOptions, UI)
export default class ModalGenerator {
  constructor(project, options, ui) {
    this.project = project;
    this.options = options;
    this.ui = ui;
  }

  execute() {
    return this.ui
      .ensureAnswer(this.options.args[0], 'What would you like to call the custom modal element?')
      .then(name => {
        let fileName = this.project.makeFileName(name);
        let className = this.project.makeClassName(name);

        this.project.elements.add(
          ProjectItem.text(`${fileName}.js`, this.generateJSSource(className)),
          ProjectItem.text(`${fileName}.html`, this.generateHTMLSource(className, name)),
          ProjectItem.text(`${fileName}.less`, this.generateCssSource(name))
        );

        return this.project.commitChanges()
          .then(() => this.ui.log(`Created ${fileName}.`));
      });
  }

  generateJSSource(className) {
    return `import { bindable, containerless } from 'aurelia-framework';

@containerless
export class ${className} {

    attached() {
        $(this.form).form({
            on: 'blur',
            inline: true,
            fields: {
                name: 'empty'
            }
        });
    }

    show(opts) {
        _.extend(this, opts);
        this.emModal.show({
            autoDimmer: false,
            hideOnApprove: false
        });
    }

    showHandler() {
        // reset
    }

    approveHandler(modal) {
        if (!$(this.form).form('is valid')) {
            toastr.error('表单验证不合法,请修改表单不合法输入!');
            return false;
        }

        modal.showDimmer();

        $.post('', {

        }, (data) => {
            if (data.success) {
                modal.hide();
                // toastr.success('操作成功!');
                // ea.publish(nsCons.EVENT_, {
                //     data: data.data
                // });
            } else {
                modal.hideDimmer();
                // toastr.error(data.data, '操作失败!');
            }
        });
    }
}
`;
  }

  generateHTMLSource(className, name) {
return `<template>
  <require from="./${name}.css"></require>
    <em-modal classes="${name}" em-modal.ref="emModal" onshow.call="showHandler($event)" onapprove.call="approveHandler($event)">
        <div slot="header"></div>
        <div slot="content">
            <div class="message icon warning ui">
                <i class="info circle icon"></i>
                <div class="header"></div>
            </div>
            <div class="ui form" ref="form">
                <div class="inline field required">
                    <label>名称</label>
                    <input type="text" name="name" value.bind="name" placeholder="">
                </div>
            </div>
        </div>
    </em-modal>
</template>`
  }

  generateCssSource(className) {
    return `.${className} {}`;
  }
}
